package com.example.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.Nullable;

public class LoginActivity extends Activity {
    /**
     * 用于控制loading的显示和隐藏
     */
    protected boolean visibility;
    private Button login;
    private ProgressBar loading;
    private EditText username;
    private EditText password;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        login = (Button) findViewById(R.id.login_login);
        loading = (ProgressBar) findViewById(R.id.login_loading);
        username = (EditText) findViewById(R.id.login_username);
        password = (EditText) findViewById(R.id.login_password);
        visibility = false;


        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new VisibilityLoading().execute(visibility);
            }
        });
    }



    class VisibilityLoading extends AsyncTask<Boolean, Boolean, Boolean> {

        @Override
        protected Boolean doInBackground(Boolean... speed) {

            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


            publishProgress(
                    username.getText().toString().equals("admin")
                    &&
                    password.getText().toString().equals("admin"));

            return true;
        }

        @Override
        protected void onProgressUpdate(Boolean... booleans) {
            if (booleans[0]) {
                Intent i = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(i);
            }
            if (!booleans[0]) {
                Toast.makeText(LoginActivity.this, "密码或账号错误！！", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onPreExecute() {
//            loading.setAnimation(AnimationUtils.makeInAnimation(LoginActivity.this, true));
            loading.setAnimation(AnimationUtils.makeInChildBottomAnimation(LoginActivity.this));
            loading.setVisibility(View.VISIBLE);
            visibility = true;
        }

        @Override
        protected void onPostExecute(Boolean leftMargin) {
            loading.setAnimation(AnimationUtils.makeOutAnimation(LoginActivity.this, false));
            loading.setVisibility(View.GONE);
//            loading.setAnimation(AnimationUtils.makeInChildBottomAnimation(LoginActivity.this));
            visibility = false;
        }

    }

}
